﻿namespace OpenAdmin.Application.Services;

/// <summary>
/// 用户服务
/// </summary>
public class UserService : ServiceBase, IUserService, ITransientDependency
{
    private readonly IRepository<SysUser, ApplicationDbContextLocator> _userRepository;
    private readonly IRepository<SysUserRole, ApplicationDbContextLocator> _userRoleRepository;
    private readonly IRoleService _roleServices;
    /// <summary>
    /// ctor
    /// </summary>
    /// <param name="userRepository"></param>
    /// <param name="roleServices"></param>
    /// <param name="userRoleRepository"></param>
    public UserService(IRepository<SysUser, ApplicationDbContextLocator> userRepository,
        IRepository<SysUserRole, ApplicationDbContextLocator> userRoleRepository,
        IRoleService roleServices)
    {
        _userRepository = userRepository;
        _roleServices = roleServices;
        _userRoleRepository = userRoleRepository;
    }
    /// <summary>
    /// 获取用户信息
    /// </summary>
    /// <returns></returns>
    public async Task<UserInfoResponseDto> GetUserInfo()
    {
        var user = await _userRepository.Entities.IgnoreQueryFilters().Where(p => !p.IsDeleted).FirstOrDefaultAsync(p => p.Id == UserIdentity.UserId);
        user.ThrowIfNull("用户不存在");

        return new UserInfoResponseDto
        {
            UserId = user.Id,
            UserName = user.UserName,
            RealName = user.RealName,
            Gender = user.Gender,
            Avatar = user.Avatar
        };
    }

    /// <summary>
    /// 分页获取用户信息
    /// </summary>
    /// <param name="requestDto"></param>
    /// <returns></returns>
    public async Task<PagedList<UserResponseDto>> GetUsersByPage(UserRequestDto requestDto)
    {
        var userQueryable = _userRepository.Entities.AsQueryable();
        if (!string.IsNullOrWhiteSpace(requestDto.Keyworld))
        {
            userQueryable = userQueryable.Where(p => p.UserName.Contains(requestDto.Keyworld));
        }
        var pageResult = await userQueryable.ToPagedListAsync(p => p.CreateTime, requestDto.PageIndex, requestDto.PageSize, Sorting.Descending);

        var users = _mapper.Map<List<UserResponseDto>>(pageResult.Items.ToList());
        var userIds = users.Select(p => p.Id).ToArray();
        var roles = await _roleServices.GetRolesByUserId(userIds);
        foreach (var user in users)
        {
            user.Roles = roles.Where(r => r.UserId == user.Id).Select(r => r.Name).ToList();
        }

        return new PagedList<UserResponseDto>
        {
            TotalCount = pageResult.TotalCount,
            PageIndex = pageResult.PageIndex,
            TotalPages = pageResult.TotalPages,
            PageSize = pageResult.PageSize,
            Items = users
        };
    }

    /// <summary>
    /// 添加用户
    /// </summary>
    /// <param name="requestDto"></param>
    /// <returns></returns>
    public async Task AddUser(AddUserRequestDto requestDto)
    {
        var user = await _userRepository.Entities.SingleOrDefaultAsync(p => p.UserName == requestDto.UserName);
        user.ThrowIf(p => p != null, "该帐号已存在");

        requestDto.Password = MD5Encryption.MD5Encrypt32(requestDto.Password);
        user = _mapper.Map<SysUser>(requestDto);
        user.CreateBy = UserIdentity.UserId;
        user.Remark = requestDto.Remark;
        user.CreateTime = DateTime.Now;
        user.Status = 1;
        user.UserType = UserType.None;
        await _userRepository.Entities.AddAsync(user);
        var result = await _userRepository.SaveChangesAsync();
        result.ThrowIf(p => p <= 0, "添加失败");
    }

    /// <summary>
    /// 更新用户信息
    /// </summary>
    /// <param name="requestDto"></param>
    public async Task EditUser(EditUserRequestDto requestDto)
    {
        var user = await _userRepository.Entities.FindAsync(requestDto.Id);
        user.ThrowIfNull("用户不存在");

        user.RealName = requestDto.RealName;
        user.UserName = requestDto.UserName;
        user.Status = requestDto.Status;
        user.Age = requestDto.Age;
        user.Gender = requestDto.Gender;
        user.Birthday = requestDto.Birthday;
        user.Remark = requestDto.Remark;
        user.ModifyBy = UserIdentity.UserId;
        user.ModifyTime = DateTime.Now;

        var uResult = await _userRepository.SaveChangesAsync();
        uResult.ThrowIf(p => p <= 0, "更新失败");
    }

    /// <summary>
    /// 删除用户
    /// </summary>
    /// <param name="id"></param>
    public async Task DeleteUser(int id)
    {
        var user = await _userRepository.Entities.FindAsync(id);
        user.ThrowIfNull("用户不存在");

        user.IsDeleted = true;

        var dResult = await _userRepository.SaveChangesAsync();
        dResult.ThrowIf(p => p <= 0, "删除失败");
    }

    /// <summary>
    /// 分配角色
    /// </summary>
    /// <param name="requestDto"></param>
    /// <returns></returns>
    public async Task DistributionRole(DistributionRoleRequestDto requestDto)
    {
        var user = await _userRepository.Entities.FindAsync(requestDto.UserId);
        user.ThrowIfNull("用户不存在");

        var userRoles = await _userRoleRepository.Entities.Where(p => p.UserId == requestDto.UserId).ToListAsync();

        _userRoleRepository.Entities.RemoveRange(userRoles);

        var addUserRoles = requestDto.RoleIds.Select(p => new SysUserRole { UserId = requestDto.UserId, RoleId = p });

        await _userRoleRepository.Entities.AddRangeAsync(addUserRoles);

        var result = await _userRoleRepository.SaveChangesAsync();
        result.ThrowIf(p => p <= 0, "分配失败");
    }
}
